﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.ServiceModel;
using System.ServiceModel.Description;
using ChatServerOptions;
using System.IO;
using System.Security.Permissions;
using System.Security;

namespace ChatServerService
{
    public partial class ChatServerService : ServiceBase
    {
        ServiceHost myHost;
        TheServer theserver = new TheServer();
        ChatServer myserver = new ChatServer();

        public ChatServerService()
        {
            InitializeComponent();

        }

        public void OnStart()
        {
            this.OnStart(new string[1]);
        }
        protected override void OnStart(string[] args)
        {
            checkfiles();           
            myserver.Server = theserver;
            myHost = new ServiceHost(myserver);

            try
            {
                myHost.Open();

            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("Communication exception: " + ce.Message);
                myHost.Abort();
            }
            
        }

        protected override void OnStop()
        {
            myHost.Close();
        }
        
        private static void checkfiles()
        {
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Chatserver");

            FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, path);

            perm.Assert();
            if (!Directory.Exists(path))
            {
                Console.WriteLine("Creating Temproray Application Files Directory at: " + path);
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, "settings.xml");
            if (!File.Exists(path))
            {
                Console.WriteLine("Creating Temproray at: " + path);
                File.Create(path);
            }
            CodeAccessPermission.RevertAssert();
        }
    }
}
